package start.demo01.xml.domain;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.SAXException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

public class PullParseXml {
	public static List<Book> parseXml(Reader reader) throws Exception, SAXException {
		List<Book> books = new ArrayList<Book>();
		Book book = null;
		XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
		XmlPullParser parser = factory.newPullParser();
		
		parser.setInput(reader);
		
		int event = parser.getEventType();// 触发第一个事件
		while (event != XmlPullParser.END_DOCUMENT) {
			switch (event) {
			case XmlPullParser.START_TAG:
				if ("book".equals(parser.getName())) {
					book = new Book();
					book.setId(Integer.valueOf(parser.getAttributeValue(0)));
				}
				if (book != null) {
					if ("name".equals(parser.getName()))
						book.setName(parser.nextText());
					if ("author".equals(parser.getName()))
						book.setAuthor(parser.nextText());
					if ("publisher".equals(parser.getName()))
						book.setPublisher(parser.nextText());
					if ("price".equals(parser.getName()))
						book.setPrice(Float.parseFloat(parser.nextText()));
				}
				break;
			case XmlPullParser.END_TAG:
				if ("book".equals(parser.getName())) {
					books.add(book);
					book = null;
				}
			}
			event = parser.next();// 继续下一次事件
		}
		return books;
	}

	public static void main(String[] args) throws FileNotFoundException, SAXException, Exception {
		parseXml(new FileReader("books.xml")).forEach(System.out::println);
	}
}
